import matplotlib.pyplot as plt
import numpy as np


class SCIGraph:
    def __init__(self, show_legend=True, use_grid=True):
        # 设置默认字体和字号
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 中文为宋体
        plt.rcParams['font.serif'] = ['Times New Roman']  # 英文为新罗马
        plt.rcParams['axes.unicode_minus'] = False  # 正常显示负号
        plt.rcParams['font.size'] = 20  # 设置字号
        self.fig, self.ax = plt.subplots(figsize=(15, 6))
        self.lines = 0
        self.show_legend = show_legend
        self.use_grid = use_grid
        # 定义低饱和度颜色方案
        self.colors = ['#9E9E9E', '#607D8B', '#795548', '#BDBDBD', '#CFD8DC']
        self.current_color_index = 0

    def plot(self, x, y, label, line_style='-', line_width=2, color=None):
        # 如果未指定颜色，则从默认颜色列表中选择
        if color is None:
            color = self.colors[self.current_color_index]
            self.current_color_index = (self.current_color_index + 1) % len(self.colors)
        self.ax.plot(x, y, label=label, linestyle=line_style, linewidth=line_width, color=color)
        self.lines += 1

    def set_axes_labels(self, x_label, y_label):
        """设置横纵坐标的标签"""
        self.ax.set_xlabel(x_label)
        self.ax.set_ylabel(y_label)

    def finalize_plot(self):
        self.ax.grid(self.use_grid)
        if self.show_legend and self.lines >= 2:
            self.ax.legend(loc='upper left', bbox_to_anchor=(0, 1.15), ncol=self.lines)
        self.lines = 0  # 重置线的计数器
        plt.show()

    def save_fig(self, filename, file_type='svg'):
        if self.show_legend:
            plt.savefig(f'{filename}.{file_type}', bbox_inches='tight', format=file_type)
        else:
            plt.savefig(f'{filename}.{file_type}', format=file_type)





# 示例数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

graph = SCIGraph(show_legend=True, use_grid=True)
# 设置横纵坐标的标签
graph.set_axes_labels('时间 (seconds)', 'Amplitude')

# 添加两条线
graph.plot(x, y1, 'y1 标签', line_style='-', line_width=2, color='blue')
graph.plot(x, y2, 'y2 标签', line_style='--', line_width=2, color='red')

# 完成绘制并保存
graph.finalize_plot()
# graph.save_fig('trig_functions')






